import requests
import json
from config import AUTH_KEY, WX_API_URL
from logger import logger_main
from utils import retry_on_failure


@retry_on_failure()
def send_text_message(to_user, content):
    """
    发送文本消息

    参数:
    - to_user: 接收消息的用户微信ID
    - content: 消息内容
    """
    message = {
        "ToWxID": to_user,
        "Content": content,
        "MsgType": 1
    }
    response = requests.post(
        f"{WX_API_URL}/Msg/SendTxt?authcode={AUTH_KEY}",
        json=message
    )
    logger_main.debug(
        f"发送文本消息请求响应: {json.dumps(response.json(), ensure_ascii=False)}")

    # 检查业务层错误码
    data = response.json()
    if data.get("Code") == -2:
        logger_main.warning(f"远程校验失败: {data.get('Message')}")
        raise requests.exceptions.RequestException(
            f"业务错误: {data.get('Message')}")

    logger_main.info(f"✅ 消息已发送给 {to_user}")


@retry_on_failure()
def download_image(fileAesKey, fileNo):
    """
    下载图片

    参数:
    - fileAesKey: 图片的 AES 密钥
    - fileNo: 图片的文件编号

    返回:
    - 图片的BASE64,如果下载失败则返回 None
    """
    body = {
        "fileAesKey": fileAesKey,
        "fileNo": fileNo
    }
    response = requests.post(
        f"{WX_API_URL}/Tools/CdnDownloadImage?authcode={AUTH_KEY}",
        json=body,
        timeout=5
    )
    logger_main.debug(f"下载图片请求响应: {json.dumps(response.json(), ensure_ascii=False)}")

    data = response.json()
    # 检查业务层错误码
    if data.get("Code") == -2:
        logger_main.warning(f"远程校验失败: {data.get('Message')}")
        raise requests.exceptions.RequestException(
            f"业务错误: {data.get('Message')}")

    return data.get("Data", {}).get("Image", None)


def download_emoji(cdnurl):
    """
    下载表情图片

    参数:
    - cdnurl: 表情的CDN链接

    返回:
    - 表情的BASE64,如果下载失败则返回 None
    """
    import base64
    cdnurl = cdnurl.replace("&amp;", "&")
    response = requests.get(cdnurl, timeout=3)
    response.raise_for_status()
    base64_bytes = base64.b64encode(response.content)
    base64_string = base64_bytes.decode('ascii')
    return base64_string
